default_encoding = 'utf-8'
# coding: utf-8
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from rest_framework.decorators import api_view
import json
from django.db.models import Q, F
from myblog.models import MamahaoResponseContentReport, MamahaoTestRequestTestCase, MamahaoResponseReportResult, \
    MamahaoTestRequest
from myblog.mamahaoService.baseCode import getResonCode
from django.core import serializers
import logging

logger = logging.getLogger('log')
import re


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def getReportPlan(request):  # 获取报告内容
    try:
        report = MamahaoResponseContentReport.objects.all().order_by('-updata_time')[:5]
        data = json.loads(serializers.serialize("json", report))
        result = MamahaoTestRequestTestCase.objects.all().count()
        Resulreport = MamahaoResponseReportResult.objects.all().order_by('-updata_time')[:7]
        ReportResul = json.loads(serializers.serialize("json", Resulreport))
        for i in range(len(ReportResul)):
            creatTime = ReportResul[i]["fields"]["creat_time"]
            updata_time = ReportResul[i]["fields"]["updata_time"]
            ReportResul[i]["fields"]["creat_time"] = re.split('[TZ.]', creatTime)[0]
            ReportResul[i]["fields"]["updata_time"] = re.split('[TZ.]', updata_time)[0]
        response = getResonCode().getSuccess()
        response["ReportResul"] = ReportResul
        response["data"] = data
        response["result"] = result

        return JsonResponse(response)
    except Exception as e:
        logging.error(e)
        response = getResonCode().getErorr()
        return JsonResponse(response)


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def getReportCase(request):  # 获取报告用例
    data = json.loads(request.body)
    try:
        print(data)
        report = MamahaoResponseContentReport.objects.filter(plan_id=data["id"]).get()
        listcast = MamahaoTestRequestTestCase.objects.filter(case_id__in=eval(report.store_test_case)).filter(
            Q(case_name__icontains=data["case_name"]) & Q(request_code__icontains=data["request_code"]))
        caseReport = json.loads(serializers.serialize("json", listcast))
        list_case_request_id = []
        for i in range(len(caseReport)):
            if caseReport[i]["fields"]["request_response"] == "":
                request_response = caseReport[i]["fields"]["request_response"]
            else:
                request_response = eval(caseReport[i]["fields"]["request_response"])
            caseReport[i]["fields"]["request_response"] = json.dumps(request_response)
            list_case_request_id.append(caseReport[i]["fields"]["case_request_id"])

        request = MamahaoTestRequest.objects.filter(request_id__in=list_case_request_id)
        requestResul = json.loads(serializers.serialize("json", request))
        for i in range(len(caseReport)):
            for j in range(len(requestResul)):
                if int(caseReport[i]["fields"]["case_request_id"]) == int(requestResul[j]["pk"]):
                    caseReport[i]["fields"]["request_address"] = requestResul[j]["fields"]["request_address"]
                    caseReport[i]["fields"]["request_mode"] = requestResul[j]["fields"]["request_mode"]
        response = getResonCode().getSuccess()
        response["data"] = caseReport
        return JsonResponse(response)
    except EOFError as e:
        logging.error(e)
        response = getResonCode().getErorr()
        return JsonResponse(response)
